package com.honeywen.mymvc.leetcode;


/**
 * 61. 旋转链表
 * https://leetcode-cn.com/problems/rotate-list/
 *
 * @author wangwei
 * @date 2019/5/26
 */
public class RotateRightTest {

    private static void print(ListNode node) {
        System.out.println();
        while (node != null) {
            System.out.print(node.val + "->");
            node = node.next;
        }
        System.out.println();
    }


    public static ListNode rotateRight2(ListNode head, int k) {

        ListNode node = head;

        int len = 1;
        while (node.next != null) {
            len++;
            node = node.next;
        }
        node.next = head;

        k %= len;

        for (int i = 0; i < len - k; i++) {

            node = node.next;
        }

        head = node.next;
        node.next = null;
        return head;

    }


    public static ListNode rotateRight(ListNode head, int k) {

        if (k < 1 || head == null) {
            return head;
        }


        ListNode node = head;
        int len = 0;
        while (node != null) {
            len++;
            node = node.next;
        }
        node = head;

        ListNode prev = null;
        if (len < k) {
            k %= len;
        }
        for (int i = 0; i < len - k; i++) {
            prev = node;
            node = node.next;

            if (node == null) {
                prev = null;
                node = head;
            }

        }

        if (prev == null) {
            return head;
        }
        prev.next = null;

        ListNode newHead = node;
        while (node.next != null) {
            node = node.next;
        }
        node.next = head;


        return newHead;


    }


    public static void main(String[] args) {
        ListNode n1 = new ListNode(1);
//        ListNode n2 = new ListNode(2);
//        ListNode n3 = new ListNode(3);
//        ListNode n4 = new ListNode(4);
//        ListNode n5 = new ListNode(5);
//        n1.next = n2;
//        n2.next = n3;
//        n3.next = n4;
//        n4.next = n5;

        print(n1);

        print(rotateRight2(n1, 1));

    }
}
